package com.nbjtjc.safe.service.safe;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nbjtjc.safe.bean.Result;
import com.nbjtjc.safe.mapper.safe.SafeBasisClassifyMapper;
import com.nbjtjc.safe.model.safe.SafeBasisClassify;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SafeBasisClassifyServiceImpl {


    @Autowired
    private SafeBasisClassifyMapper safeBasisClassifyMapper;


    public Result find(SafeBasisClassify safeBasisClassify) {
        Result result = new Result();
        List<SafeBasisClassify> safeBasisClassifyList = safeBasisClassifyMapper.select(safeBasisClassify);
        List<SafeBasisClassify> classifies = new ArrayList<>();
        compareList(safeBasisClassifyList, classifies);
        result.setData(classifies);
        return result;
    }

    public void compareList(List<SafeBasisClassify> safeBasisClassifyList, List<SafeBasisClassify> classifies) {
        Map<String, List<SafeBasisClassify>> classifyMap = new HashMap<>();
        safeBasisClassifyList.forEach(classify -> {
            if (classifyMap.containsKey(classify.getPid())) {
                classifyMap.get(classify.getPid()).add(classify);
            } else {
                List<SafeBasisClassify> classifyList = new ArrayList<>();
                classifyList.add(classify);
                classifyMap.put(classify.getPid(), classifyList);
            }
        });
        classifies.addAll(classifyMap.get("00"));
        classifyMap.remove("00");
        compare(classifies, classifyMap);
    }

    public void compare(List<SafeBasisClassify> classifies, Map<String, List<SafeBasisClassify>> classifyMap) {

        List<SafeBasisClassify> safeBasisClassifies = new ArrayList<>();
        classifies.forEach(classify -> {
            if (classifyMap.containsKey(classify.getId())) {
                classify.setChildren(classifyMap.get(classify.getId()));
                safeBasisClassifies.addAll(classify.getChildren());
                classifyMap.remove(classify.getId());
            }
        });
        if (safeBasisClassifies.size() > 0) {
            compare(safeBasisClassifies, classifyMap);
        }
    }


    @Transactional
    public Result add(SafeBasisClassify safeBasisClassify) {
        Result result = new Result();
        safeBasisClassifyMapper.insert(safeBasisClassify);
        result.setData(safeBasisClassify);
        return result;
    }
}
